<template>
    <el-dialog :model-value="props.giveRoleDialog" title="分配角色" :before-close="() => emit('showGiveRoleDialog', false)">
      <p>当前的用户: {{userInfo.name}}</p>
      <p style="margin: 20px 0">当前的角色: {{userInfo.role}}</p>
      <span>分配角色 </span>
      <el-select v-model="selectValue" placeholder="请选择" size="large">
        <el-option v-for="item in selectOption" :key="item.id" :value="item.id" :label="item.label"></el-option>
      </el-select>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="emit('showGiveRoleDialog', false)">取消</el-button>
          <el-button type="primary" @click="() => saveRle()">确定</el-button>
        </div>
      </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, watch, ref } from 'vue';
import { GetRolesFnc, SaveRolesFnc } from '@/api/user'
import type { itemType } from './type';

const props = defineProps({
  giveRoleDialog: {type: Boolean, required: true},
  roleID: {type: Number, required: true},
  username: {type: String, required: true},
  rolename: {type: String, required: true},
  pageNow: {type: Number, required: true},
  pageSize: {type: Number, required: true}
})

const userInfo = reactive({ name: '', role: '' }) // 分配角色信息
const selectValue = ref('') // 分配角色选项
const selectOption = ref<itemType[]>([]) // 角色选项 
const id = ref(0)

watch([() => props.roleID, () => props.username, () =>  props.rolename], async ([newID, newName, newRole]) => {
  id.value = newID
  userInfo.name = newName
  userInfo.role = newRole

  // 获得下拉菜单的选项
  const res = await GetRolesFnc()
  if(res.data.meta.status === 200) {
    selectOption.value = res.data.data.map((item: {id: number, roleName: string}) => {
      return {
        value: item.roleName,
        label: item.roleName,
        id: item.id
      }
    })
  }
})

const emit = defineEmits(['showGiveRoleDialog', 'init'])

// 保存角色
const saveRle = async () => {
  const res = await SaveRolesFnc(id.value, {rid: selectValue.value})
  if(res.data.meta.status === 200) {
    ElMessage({type: 'success', message: '分配角色成功', duration: 1000, onClose: () => {
      emit('showGiveRoleDialog', false)
      userInfo.name = ''
      userInfo.role = ''
      selectValue.value = ''
      emit('init', props.pageNow, props.pageSize)
    }})
  } else {
    ElMessage({type: 'error', message: res.data.meta.msg, duration: 1000, onClose: () => { emit('showGiveRoleDialog', false), selectValue.value = '' }})
  }
}
</script>